package org.mysocial.services.business.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.mysocial.datamodel.Account;
import org.mysocial.datamodel.Comment;
import org.mysocial.datamodel.CommentNotification;
import org.mysocial.datamodel.Friendship;
import org.mysocial.datamodel.FriendshipRequestNotification;
import org.mysocial.datamodel.Like;
import org.mysocial.datamodel.LikeNotification;
import org.mysocial.datamodel.Message;
import org.mysocial.datamodel.MessageDestination;
import org.mysocial.datamodel.MessageNotification;
import org.mysocial.datamodel.MultipleDestinationMessage;
import org.mysocial.datamodel.SingleDestinationMessage;
import org.mysocial.services.business.NotificationBusiness;
import org.mysocial.services.dao.NotificationDAO;

/**
 * Session Bean implementation class NotificationBusinessImpl
 */
@Stateless
public class NotificationBusinessImpl implements NotificationBusiness
{

	@EJB
	private NotificationDAO notificationDAO;

	/**
	 * Default constructor.
	 */
	public NotificationBusinessImpl()
	{
		// TODO Auto-generated constructor stub
	}

	@Override
	public CommentNotification notifyComment(Account account, Comment comment)
	{
		final CommentNotification notification = new CommentNotification();
		notification.setSourceAccount(comment.getAccount());
		notification.setTargetPost(comment.getPost());

		notificationDAO.persist(notification);

		return notification;
	}

	@Override
	public FriendshipRequestNotification notifyFriendshipRequest(
	    Friendship friendship)
	{
		FriendshipRequestNotification notification = new FriendshipRequestNotification();
		notification.setAccount(friendship.getToAccount());
		notification.setFriendship(friendship);

		return (FriendshipRequestNotification) notificationDAO
		    .persist(notification);
	}

	@Override
	public LikeNotification notifyLike(Account account, Like like)
	{
		LikeNotification notification = new LikeNotification();
		notification.setAccount(account);
		notification.setLike(like);

		return (LikeNotification) notificationDAO.persist(notification);
	}

	@Override
	public List<MessageNotification> notifyMessage(Message message)
	{
		List<Account> accounts = new ArrayList<Account>();

		if (message instanceof SingleDestinationMessage)
		{
			accounts.add(((SingleDestinationMessage) message).getReceiver());
		} else
		{
			for (MessageDestination destination : ((MultipleDestinationMessage) message)
			    .getReceivers())
			{
				accounts.add(destination.getReceiver());
			}
		}

		List<MessageNotification> notifications = new ArrayList<MessageNotification>();
		MessageNotification notification;

		for (Account account : accounts)
		{
			notification = new MessageNotification();
			notification.setMessage(message);
			notification.setAccount(account);

			notificationDAO.persist(notification);
			notifications.add(notification);
		}

		return notifications;
	}

}
